import 'package:elevator/model/signal_count_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_expandable_table/flutter_expandable_table.dart';
import 'package:get/get.dart';

import '../../../../../../get/intl_keys.dart';
import '../../../../../../model/build_info.dart';
import '../../../../../../model/lift_info.dart';
import '../../../../../../utils/utils_logger.dart';
import 'package:date_format/date_format.dart';
import 'package:mysql1/mysql1.dart' as mysql;

class MessagesLogic extends GetxController {
  BuildInfo buildInfo = BuildInfo();
  LiftInfo liftInfo = LiftInfo();
  var selectOneMonth = true.obs;
  List<SignalCountInfo> signalCounts =  [];

  late ExpandableTableController controller;

  @override
  void onInit() {
    super.onInit();
    initController();
  }

  @override
  void onReady() {
    super.onReady();
    oneMonth();
  }

  oneMonth() {
    selectOneMonth.value = true;
    selectOneMonth.refresh();
    String endDate  = formatDate(DateTime.now(), [yyyy, '-', mm, '-', dd," ","HH",":","nn",":","ss"]);
    String  startDate = formatDate(DateTime.now().subtract(const Duration(days:30)), [yyyy, '-', mm, '-', dd," ","HH",":","nn",":","ss"]);
    logd("oneMonth:startDate=$startDate,endDate=$endDate");
    queryBuildErrorData(buildInfo.buildId,liftInfo.order.toString(),startDate,endDate);
  }

  halfaMonth() {
    selectOneMonth.value = false;
    selectOneMonth.refresh();
    logd("halfaMonth:"+selectOneMonth.value.toString());
    String endDate  = formatDate(DateTime.now(), [yyyy, '-', mm, '-', dd," ","HH",":","nn",":","ss"]);
    String startDate = formatDate(DateTime.now().subtract(const Duration(days:15)), [yyyy, '-', mm, '-', dd," ","HH",":","nn",":","ss"]);
    logd("halfaMonth:startDate=$startDate,endDate=$endDate");
    queryBuildErrorData(buildInfo.buildId,liftInfo.order.toString(),startDate,endDate);
  }


  /// 查询错误信息
  queryBuildErrorData(String buildId,String liftId,String startDate,String endDate ) async {
    debugPrint("start queryBuildErrorData $buildId");
    var settings = mysql.ConnectionSettings(
        host: '36.141.45.30',
        port: 43306,
        user: 'root',
        password: 'adminemqx123',
        db: 'liftdb_$buildId',
        useCompression: false,
        timeout:const Duration(seconds: 60),
        maxPacketSize:16 * 1024 * 1024 *1024,
        characterSet: mysql.CharacterSet.UTF8MB4);
    var conn = await mysql.MySqlConnection.connect(settings);

    var dataResluts = await conn
        .query("select SignalTrigger,SUM(count) as count FROM tbsignalrecord WHERE TrgDateTime between '$startDate' and '$endDate' and liftAdr = '$liftId' GROUP BY SignalTrigger");

    Map<String,SignalCountInfo> signalCountMap = SignalCountInfo.buildSignalInfoMap();
    for (var row in dataResluts) {
      SignalCountInfo.builder(row,signalCountMap);
    }
    conn.close();
    List<SignalCountInfo> countInfos = [];
    for(SignalCountInfo info in signalCountMap.values){
      countInfos.add(info);
    }
    signalCounts = countInfos;
    controller.rows = buildRows();
    debugPrint("楼盘 $buildId $liftId signalCount加载$startDate至$endDate完毕：${countInfos.length}条");
  }

  double itemWidth = 60;
  Color _accentColor = Color(0xFF0d2026); //background

  List<ExpandableTableRow> buildRows(){
    const int columnsCount = 3;
    int rowsCount = 10;
    final List<ExpandableTableRow> rows = List.generate(
      rowsCount,
          (rowIndex) => ExpandableTableRow(
        height: 50,
        firstCell: _buildCell(rowIndex),
        cells: List<ExpandableTableCell>.generate(
          columnsCount - 1,
              (columnIndex) => _buildCell2(rowIndex, columnIndex),
        ),
      ),
    );
    return rows;
  }

  initController(){
    List<ExpandableTableRow> rows = buildRows();

    controller = ExpandableTableController(
      firstHeaderCell: _buildFirstCell('', celColor: Colors.green),
      firstColumnWidth: itemWidth,
      headerHeight: 60,

      headers: [
        ExpandableTableHeader(
          width: itemWidth * 2,
          cell: _buildFirstCell(IntlKeys.specialMsg.tr, celColor: Colors.green),
        ),
        ExpandableTableHeader(
          width: itemWidth,
          cell: _buildFirstCell(IntlKeys.times.tr, celColor: Colors.green),
        ),
      ],
      scrollShadowColor: _accentColor,
      rows: rows,
      visibleScrollbar: false,
      trackVisibilityScrollbar: false,
      thumbVisibilityScrollbar: false,
    );


  }

  ExpandableTableCell _buildFirstCell(String content, {CellBuilder? builder, Color? celColor}) {

    return ExpandableTableCell(
      child: Container(
        decoration: BoxDecoration(
          color: celColor,
          border: Border.all(color: Colors.grey, width: 1),
        ),
        child: GestureDetector(
          onTap: () {
            print('点击项目$content');
          },
          child: Center(
            child: Text(
              content,
              style: const TextStyle(color: Colors.white),
            ),
          ),
        ),
      ),
      builder: builder,
    );
  }

  ExpandableTableCell _buildCell(int index, {CellBuilder? builder}) {
    String content = (index + 1).toString();

    return ExpandableTableCell(
      child: Container(
        // color: Colors.yellowAccent,
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey, width: 1),
        ),
        child: GestureDetector(
          onTap: () {
            print('点击$content');
          },
          child: Center(
            child: Text(
              content,
              style: const TextStyle(color: Colors.black),
            ),
          ),
        ),
      ),
      builder: builder,
    );
  }


  ExpandableTableCell _buildCell2(int row, int col, {CellBuilder? builder}) {
    String content = '';

    if (col == 0) {
      switch (row) {
        case 0:
          content = IntlKeys.errorLoop.tr;
          break;
        case 1:
          content = IntlKeys.allDoorOpen.tr;
          break;
        case 2:
          content = IntlKeys.safetyKnifeTriggers.tr;
          break;
        case 3:
          content = IntlKeys.error.tr;
          break;
        case 4:
          content = IntlKeys.machineFallingGateLock.tr;
          break;
        case 5:
          content = IntlKeys.powerFailure.tr;
          break;
        case 6:
          content = IntlKeys.doorFailure.tr;
          break;
        case 7:
          content = IntlKeys.doorOperationOverload.tr;
          break;
        case 8:
          content = IntlKeys.doorFullyOpenNoGateLock.tr;
          break;
        case 9:
          content = IntlKeys.doorPcbFailure.tr;
          break;
      }
    } else if (col == 1) {
      if(signalCounts.length>row){
        content = signalCounts[row].count.toString();
      }
    }

    return ExpandableTableCell(
      child: Container(
        // color: Colors.yellowAccent,
        decoration: BoxDecoration(
          border: Border.all(color: Colors.grey, width: 1),
        ),
        child: GestureDetector(
          onTap: () {
            print('点击项目$content');
          },
          child: Center(
            child: Text(
              content,
              style: const TextStyle(color: Colors.black),
            ),
          ),
        ),
      ),
      builder: builder,
    );
  }

}
